package com.atguigu.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: 叶子
 * @date: 2022/01/17 17:07
 * 使用一个Buffer完成文件拷贝
 * 使用FileChannel和方法read,write,完成文件的拷贝
 **/
public class NIOFileChannel03 {
    public static void main(String[] args) throws IOException {
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();
        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (true) {//循环读取
//          下面这一行是清空buffer
            byteBuffer.clear();//没有这一行会死循环读到0
            int read = fileChannel01.read(byteBuffer);
            System.out.println("read=" + read);
            if (read == -1) {//表示读完
                break;
            }
//            将buffer中的数据写入到fileChannel02 --- 2.txt
            byteBuffer.flip();//position与limit反转过后，如果不进行byteBuffer.clear()就一直读到0
            fileChannel02.write(byteBuffer);
        }
//        关闭相关的流
        fileInputStream.close();
        fileOutputStream.close();
    }
}